<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
        <head><p>
                <style>
                        .error {color: #FF0000;}
                </style>
                <title>New User</title>
				<link type="text/css" rel="stylesheet" href="../stylesheet.css">
        </head>
        <body>
            <h1 class="title">Milestone - New Account Sign-Up</h1>
        <?php
				//initialize all variables to be empty strings
                $first = $last = $email = $password = $phone = $confPassword =  '';
                $firstErr = $lastErr = $emailErr = $passwordErr = $phoneErr = '';
                $arrCheck = 0;
                /*
                        This code block is accessed whenever a form has been submitted.
                        It checks that required fields are complete and also checks the format with preg_match.
                        Special characters are removed using the clean_field function.
                */
                if ($_SERVER["REQUEST_METHOD"] == "POST")
                {
                        if (empty ($_POST["first"])) /
						{
                                $firstErr = "Please enter a first name";
                        }
                        else 
						{
                                $first = clean_field ($_POST["first"]);
                                if (!preg_match("/^[a-zA-Z ]*$/", $first))//regex to check that first name is correctly formatted
								{
                                        $firstErr = "Names can only include letters and white space.";
                                }
                        }
                       
					   if (empty ($_POST["last"])) 
					   {
                                $lastErr = "Please enter a last name";
                        }
                        else 
						{
                                $last = clean_field ($_POST["last"]);
                                if (!preg_match("/^[a-zA-Z ]*$/", $last)) //regex to ensure that last name is correctly formatted
								{
                                        $lastErr = "Names can only include letters and white space.";
                                }
                        }	
                       
                        if (empty ($_POST["email"])) 
						{
                                $emailErr = "Please enter a valid email address";
                        }
                        else 
						{
                                $email = clean_field ($_POST["email"]);
                                if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email))//regex to ensure that email is correctly formatted 
								{
                                        $emailErr = "Invalid email format. (ex: example@email.com)";
                                }
                        }
                       
                        if (empty ($_POST["password"])) 
						{
                                $passwordErr = "Please enter a valid password";
                        }
                        else 
						{	
                                $password = clean_field ($_POST["password"]);
								$confPassword = clean_field ($_POST["confPassword"]);
                                if (!preg_match("/^(?=.*[a-zA-Z])(?=.*[0-9])(?=.*[a-zA-Z]).{6,}$/", $password)) 
								{
                                        $passwordErr = "Invalid password. Password must be at least 6 characters long and have at least one number and one letter.";
                                }
								else if ($password != $confPassword) 
								{
									    $passwordErr = "Passwords do not match!";
								}
                                else 
								{ 
										//Generate a hashed password using a randomly generated salt. Store that salt in the database.
                                        $salt = openssl_random_pseudo_bytes(8);
                                        $salt = bin2hex($salt);
                                        $hashed_password = hash("sha256", $password . $salt);
                                }
                        }
                       
                        if (!empty ($_POST["phone"])) 
						{
                                $phone = clean_field ($_POST["phone"]);
                                if (!preg_match("/^\d{3}-\d{3}-\d{4}$/", $phone)) 
								{
                                        $phoneErr = "Invalid phone format. (ex: 123-456-7890)";
                                }
                        }
                       

                        $errArray = array($firstErr, $lastErr, $emailErr, $passwordErr, $phoneErr);
                       
                        //Checking to see if there are any errors in the form submission.
                        foreach ($errArray as $key => $value) 
						{
                                if (!empty($value))
                                        $arrCheck = 1;
                        }

                        if ($arrCheck == 0) 
						{
                                $username = 'root';
                                $pw = 'password';

                                //Connect to the database.
                                $con = mysqli_connect ("localhost", $username, $pw, 'milestone');

                                if (mysqli_connect_errno()) 
								{
                                  echo "Failed to connect to MySQL: " . mysqli_connect_error();
                                }
                               
                                $phone2 = str_replace("-", "", $phone);
                                // Query for inserting all form data into the user table
                                $query_result = mysqli_query ($con, "insert into users(email, FirstName, LastName, phone, password)
                                        values('$email', '$first', '$last', '$phone2', '$password')");
									
								if (!($query_result)) 
								{
									echo '<span class="error">DATABASE FAILED TO ADD USER!</span>';
								}
                                //There should be another query for uploading the actual file for the abstract.
                                mysqli_close($con);
                               
                                //Redirect to the home page after the form is successfully submitted.
                                header("Location: login.php");
                        }
                }
                //This function removes special characters from user input. Prevents script injection
                function clean_field ($data)
                {
                        $data = trim($data);
                        $data = stripslashes($data);
                        $data = htmlspecialchars($data);
                        return $data;
                }
                ?>

                <p><span class="error">* indicates required fields</span></p>
                <form method="post" action="<?php echo htmlspecialchars($_SERVER["REQUEST_URI"]);?>">
                        E-Mail: <input type="text" name="email" value="<?php echo $email?>">
                        <span class="error">* <?php echo $emailErr;?></span><br><br>
                       
                        First Name: <input type="text" name="first" value="<?php echo $first?>">
                        <span class="error">* <?php echo $firstErr;?></span><br><br>
                       
					   Last Name: <input type="text" name="last" value="<?php echo $last?>">
                        <span class="error">* <?php echo $lastErr;?></span><br><br>
                       
                        Phone Number: <input type="text" name="phone" value="<?php echo $phone?>">
                        <span class="error"> <?php echo $phoneErr;?></span><br><br>
						
                       Password: <input type="password" name="password" value="<?php echo $password?>">
                        <span class="error">* <?php echo $passwordErr;?></span><br><br>
						
						Confirm Password: <input type="password" name="confPassword" value="<?php echo $confPassword?>">
                        <span class="error">* <?php echo $passwordErr;?></span><br><br>
						
                        <input type="submit" name="submit" value="Submit">
                    </div>
                </form>
            <a href="eng_login.php" id="back">Back</a>
        </body>
</html>
